package com.whfc.hdc.redis.impl;

import com.alibaba.fastjson.JSON;
import com.whfc.hdc.dto.HdcAccessTokenDTO;
import com.whfc.hdc.redis.HdcTokenRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-07-20 09:19
 */
@Repository
public class HdcTokenRedisDaoImpl implements HdcTokenRedisDao {

    private static final String HDC_ACCESS_TOKEN_KEY = "hdc:open:token:{0}";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void setAccessToken(String accessToken, HdcAccessTokenDTO accessTokenDTO, long expiresIn) {
        String key = MessageFormat.format(HDC_ACCESS_TOKEN_KEY, accessToken);
        String tokenStr = JSON.toJSONString(accessTokenDTO);
        redisTemplate.opsForValue().set(key, tokenStr, expiresIn, TimeUnit.MILLISECONDS);
    }

    @Override
    public HdcAccessTokenDTO getAccessToken(String accessToken) {
        String key = MessageFormat.format(HDC_ACCESS_TOKEN_KEY, accessToken);
        String tokenStr = redisTemplate.opsForValue().get(key);
        HdcAccessTokenDTO tokenDTO = null;
        if (StringUtils.isNotBlank(tokenStr)) {
            tokenDTO = JSON.parseObject(tokenStr, HdcAccessTokenDTO.class);
        }
        return tokenDTO;
    }

}
